# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function

from ..ops import Ref, Sum
from ..base import OpsFeature

from .tp import TP
from .volume import Volume

class MFI(OpsFeature):
    """Technical Indicator - MFI

    - MF  = TP * VOLUME
    - PMF = Sum(IF(TP > REF(TP, 1), MF, 0), N)
    - NMF = Sum(IF(TP < REF(TP, 1), MF, 0), N)
    - MFI = 100 - (100 / (1 + PMF/NMF))
    """
    def __init__(self, N=14):
        self.N = N

    def __str__(self):
        name = type(self).__name__.lower()
        if self.N != 14:
            name += '_'+str(self.N)
        return name

    def _load_internal(self, instrument, start_time, end_time, freq):
        diff = TP() - Ref(TP(), 1)
        mf = TP() * Volume()
        pmf = Sum((diff > 0) * mf, self.N)
        nmf = Sum((diff < 0) * mf, self.N) + 1e-12 # divide by 0
        mfi = 100 - 100 / (1 + pmf/nmf)
        return mfi.load(instrument, start_time, end_time, freq)
